package com.google.project.client.Admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.UsersService;
import com.google.project.client.Service.UsersServiceAsync;
import com.google.project.shared.UsersDTO;

public class ADMAccountList extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided = true) CellTable<UsersDTO> ctbUserList = new CellTable<UsersDTO>();
	@UiField ListBox cbUserGroup;
	@UiField ListBox cbStatus;
	@UiField TextBox txtUserCode;
	@UiField Button btnSearch;
	@UiField SimplePager pager;
	@UiField Button btnCreateAccount;
	@UiField TextBox txtFullName;
	@UiField TextBox txtUserName;

	final MultiSelectionModel<UsersDTO> selectionModel = new MultiSelectionModel<UsersDTO>();
	private final UsersServiceAsync userService = GWT.create(UsersService.class);
	private List<UsersDTO> usersDTOList = new ArrayList<UsersDTO>();
	private List<UsersDTO> accList = new ArrayList<UsersDTO>();
	private String status;

	interface Binder extends UiBinder<Widget, ADMAccountList> {
	}

	public ADMAccountList() {
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	txtUserName.setFocus(true);
	        }
	    });
		initCbStatus();
		initCbGroup();
		bindData();
	}

	public ADMAccountList(int _status) {
		this.status = _status + "";
		initWidget(binder.createAndBindUi(this));
		Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand () {
	        public void execute () {
	        	txtUserName.setFocus(true);
	        }
	    });
		initCbStatus(status);
		initCbGroup();
		searchFunction(status.trim());
	}

	public void initCbGroup() {
		cbUserGroup.addItem("---Tất cả---", "0");
		cbUserGroup.addItem("Giám đốc", "1");
		cbUserGroup.addItem("Quản lý", "2");
		cbUserGroup.addItem("Chỉ huy công trường", "3");
		cbUserGroup.addItem("Quản lý nhân sự", "4");
		cbUserGroup.addItem("Nhân viên", "5");
		cbUserGroup.addItem("Admin","6");
		cbUserGroup.setSelectedIndex(0);
	}

	public void initCbStatus() {
		cbStatus.addItem("---Tất cả---", "0");
		cbStatus.addItem("Chưa có tài khoản", "1");
		cbStatus.addItem("Đang hoạt động", "2");
		cbStatus.addItem("Đã bị khóa", "3");
		cbStatus.setSelectedIndex(0);
	}
	
	public void initCbStatus(String _status) {
		cbStatus.addItem("---Tất cả---", "0");
		cbStatus.addItem("Chưa có tài khoản", "1");
		cbStatus.addItem("Đang hoạt động", "2");
		cbStatus.addItem("Đã bị khóa", "3");
		int index = 0;
		if(_status.equals("1")) {
			index = 1;
		} else if(_status.equals("2")) {
			index = 2;
		} else if(_status.equals("3")) {
			index = 3;
		}
		cbStatus.setSelectedIndex(index);
	}
	
	public void bindData() {
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onSuccess(List<UsersDTO> result) {
				if(result.size() == 0) {
					Window.alert("Không có dữ liệu!");
				}
				for(UsersDTO usersDTO : result) {
					usersDTOList.add(usersDTO);
				}
				loadData(result);
				initTable();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình lấy thông tin tài khoản!");
			}
		});
	}

	public void loadData(List<UsersDTO> userList) {
		
		ListDataProvider<UsersDTO> dataProvider = new ListDataProvider<UsersDTO>();

		// Connect the table to the data provider.
		dataProvider.addDataDisplay(ctbUserList);

		// Add the data to the data provider, which automatically pushes it to
		// the widget
		List<UsersDTO> list = dataProvider.getList();
		for(int i = 0; i < userList.size(); i++) {
			userList.get(i).setIndex(i+1);
			list.add(userList.get(i));
		}
		// SimplePager
		pager.setDisplay(ctbUserList);
	}
	
	public void initTable() {
		//STT
		TextColumn<UsersDTO> indexColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO userCode) {
				return userCode.getIndex()+"";
			}
		};

		//Check box
		ctbUserList.setSelectionModel(selectionModel, DefaultSelectionEventManager.<UsersDTO> createCheckboxManager());
		Column<UsersDTO, Boolean> checkColumn = new Column<UsersDTO, Boolean>(new CheckboxCell(true, false)) {
			@Override
			public Boolean getValue(UsersDTO object) {
				// Get the value from the selection model.
				return selectionModel.isSelected(object);
			}
		};

		//Ma nhan vien
		Column<UsersDTO, String> userCodeColumn = new Column<UsersDTO, String>(new ClickableTextCell()) {
			@Override
			public String getValue(UsersDTO user) {
				return user.getUserCode();
			}
		};
		userCodeColumn.setFieldUpdater(new FieldUpdater<UsersDTO, String>() {
			@Override
			public void update(int index, UsersDTO user, String value) {
				if(user.getStatus().equals("1")) {	//Users chua co tai khoan
					Window.alert("Tài khoản chưa được tạo!");
				} else if(user.getStatus().equals("2")) {	//Users da co tai khoan
					ADMEntrypoint.get().ADMCreateAccount(user.getUserId());
				}
			}

		});

		//Ten tai khoan
		TextColumn<UsersDTO> accountNameColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getUserName();
			}
		};
		
		//Ten nhan vien
		TextColumn<UsersDTO> userNameColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getFullName();
			}
		};
				
		// email
		TextColumn<UsersDTO> emailColumn = new TextColumn<UsersDTO>() {
			@Override
			public String getValue(UsersDTO user) {
				return user.getEmail();
			}
		};
		
		ctbUserList.setWidth("100%", true);
		ctbUserList.setPageSize(5);
		ctbUserList.setPageStart(0);
		ctbUserList.setStyleName("ttable");
		
		ctbUserList.addColumn(indexColumn, "STT");
		ctbUserList.setColumnWidth(indexColumn, 40, Unit.PX);
		
		ctbUserList.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant(""));
		ctbUserList.setColumnWidth(checkColumn, 40, Unit.PX);
		
		ctbUserList.addColumn(userCodeColumn, "Mã nhân viên");
		userCodeColumn.setCellStyleNames("celltable");
		ctbUserList.setColumnWidth(userCodeColumn, 120, Unit.PX);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(userCodeColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		ctbUserList.addColumn(accountNameColumn, "Tên tài khoản");
		ctbUserList.setColumnWidth(accountNameColumn, 20.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(accountNameColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);

		ctbUserList.addColumn(userNameColumn, "Tên nhân viên");
		ctbUserList.setColumnWidth(userNameColumn, 20.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(userNameColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
		
		ctbUserList.addColumn(emailColumn, "Email");
		ctbUserList.setColumnWidth(emailColumn, 20.0, Unit.PCT);
		ctbUserList.getColumn(ctbUserList.getColumnIndex(emailColumn)).setHorizontalAlignment(HasAlignment.ALIGN_LEFT);
		
	}

	// search
	@UiHandler("btnSearch")
	void onBtnSearchClick(ClickEvent event) {
		searchFunction();
	}

	//Ham search
	private void searchFunction() {
		String userName = txtUserName.getText().trim();
		String userCode = txtUserCode.getText().trim();
		String fullName = txtFullName.getText().trim();
		String accountStatus = "";
		if(cbStatus.getValue(cbStatus.getSelectedIndex()) != null) {
			accountStatus = cbStatus.getValue(cbStatus.getSelectedIndex()).trim();
		}
		Long accountGroup = -1L;
		if(cbUserGroup.getValue(cbUserGroup.getSelectedIndex()) != null) {
			accountGroup = Long.parseLong(cbUserGroup.getValue(cbUserGroup.getSelectedIndex()));
		}
		
		Boolean condition = true;
		
		List<UsersDTO> temple = new ArrayList<UsersDTO>();
		for(UsersDTO user : usersDTOList) {
			if(user.getUserName() == null){
				user.setUserName("");
			}
			if(userName != null) {
				condition = condition && (user.getUserName().contains(userName));
			}
			if(userCode != null && !userCode.equals("")) {
				condition = condition && (user.getUserCode().equals(userCode));
			}
			if(fullName != null) {
				condition = condition && (user.getFullName().contains(fullName));
			}
			
			if((cbStatus.getValue(cbStatus.getSelectedIndex()) != null) && (!cbStatus.getValue(cbStatus.getSelectedIndex()).equalsIgnoreCase("0"))) {
				condition = condition && (user.getStatus().equals(accountStatus));
			}
			if(user.getUserGroup() == null) {
				user.setUserGroup(0L);
			}
			if((cbUserGroup.getValue(cbUserGroup.getSelectedIndex()) != null) && (!cbUserGroup.getValue(cbUserGroup.getSelectedIndex()).equalsIgnoreCase("0"))) {
				condition = condition && (user.getUserGroup()== accountGroup);
			}
			if(condition) {
				temple.add(user);
			}
			condition = true;
		}
		if(temple != null) {
			loadData(temple);
		} else {
			loadData(temple);
		}
	}
	
	public void searchFunction(final String status) {
		userService.getUserList(new AsyncCallback<List<UsersDTO>>() {
			@Override
			public void onSuccess(List<UsersDTO> result) {
				usersDTOList = result;
				for(UsersDTO usersDTO : result) {
					if(usersDTO.getStatus().equals(status)) {
						accList.add(usersDTO);
					}
				}
				loadData(accList);
				initTable();
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Có lỗi trong quá trình lấy thông tin tài khoản!");
			}
		});
	}
	
	//Event click "tao tai khoan"
	@UiHandler("btnCreateAccount")
	void onBtnCreateAccountClick(ClickEvent event) {
		Set<UsersDTO> listChecked = selectionModel.getSelectedSet();
		List<UsersDTO> list = new ArrayList<UsersDTO>();
		for(UsersDTO UsersDTO : listChecked) {
			list.add(UsersDTO);
		}
		if(list.size() == 0) {
			Window.alert("Bạn chưa chọn nhân viên để tạo tài khoản!");
		} else if(list.toArray().length > 1) {
			Window.alert("Chỉ được chọn một tài khoản!");
			listChecked.clear();
			return;
		} else if(list.toArray().length == 1) {
			if(list.get(0).getStatus().equalsIgnoreCase("1")) {
				ADMEntrypoint.get().ADMCreateAccount(list.get(0).getUserId());
			} else {
				Window.alert("Người dùng đã có tài khoản!");
			}
		}
	}
}
